//
//  MQPictureMainViewController.m
//  MQ
//
//  Created by lanou on 15/10/26.
//  Copyright © 2015年 徐永祥. All rights reserved.
//

#import "MQPictureMainViewController.h"
#import "MQPictureInsterestingModel.h"
#import "MQPictureInsterestingCell.h"
#import "PKRequestManager.h"
#import "MJRefresh.h"
#import "FMDatabase.h"
#import "BigBackgroundViewController.h"
#import "MQPopupView.h"
#import "LewPopupViewAnimationDrop.h"
#import "MQSettingMainViewController.h"
#import "Reachability.h"
#import "UMSocial.h"
#import "MQFMDBManager.h"
#import "MQChangeSkin.h"
@interface MQPictureMainViewController ()<UITableViewDataSource,UITableViewDelegate,UMSocialUIDelegate>
{
    int i;
}
@property(nonatomic, strong)UITableView *picListTableView;
@property(nonatomic, strong)NSMutableArray *dataArray;//装数据的数组
@property(nonatomic, strong)NSString *urlStr;//请求数据的网址
@property(nonatomic, strong)Reachability *reach;//监听网络
@property(nonatomic, strong)NSString *shareStr;//分享的文字
@property(nonatomic, strong)UIImage *shareImage;//分享的图片
@end

@implementation MQPictureMainViewController

-(NSMutableArray *)dataArray
{
    if (_dataArray == nil) {
        self.dataArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataArray;
}

//配置数据
- (void)configureData
{
    if ([self isConnectionAvailable]) {
        [PKRequestManager requestWithType:GET urlString:self.urlStr parDic:nil finish:^(NSData *data) {
            //删除数据库全部内容
            [[MQFMDBManager shareDataBase] executeUpdate:@"DELETE FROM PICTURE"];
            
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves) error:nil];
            NSArray *itemArr = dic[@"items"];
            for (NSDictionary *itemDic in itemArr) {
                MQPictureInsterestingModel *model = [[MQPictureInsterestingModel alloc]init];
                [model setValuesForKeysWithDictionary:itemDic];
                [self.dataArray addObject:model];
                //插入数据
                [self insertDatabase:model];
            }
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            MQPictureInsterestingModel *model = [self.dataArray lastObject];
            [defaults setObject:model.update_time forKey:@"update_time"];
            
            [_picListTableView reloadData]; //刷新tableview数据
            [self.picListTableView.header endRefreshing];//结束上拉刷新
            [self.picListTableView.footer endRefreshing];//结束下拉加载
        } error:^(NSError *error) {
            
        }];

    }
    else
    {
        [self selectDataBase];
        [self noNetWorking];
        [self.picListTableView.header endRefreshing];//结束上拉刷新
        [self.picListTableView.footer endRefreshing];//结束下拉加载
    }

}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"趣图逗乐";
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    //一键换肤
    NSString *picStr = [user valueForKey:@"picStr"];
    UIImageView *BigImageView = [[UIImageView alloc]initWithFrame:self.view.bounds];
    [BigImageView setImage:[UIImage imageNamed:picStr]];
    [self.view addSubview:BigImageView];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"一键换肤" style:(UIBarButtonItemStyleDone) target:self action:@selector(changeSkin)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    //打开数据库创建表
    [MQFMDBManager openDataBase:[MQFMDBManager shareDataBase] update:@"CREATE TABLE PICTURE(wbody text, wpic_middle text, wpic_m_height text, wpic_m_width text, likes text, comments text)"];
    [MQFMDBManager openDataBase:[MQFMDBManager shareDataBase] update:@"CREATE TABLE PICTURES(wbody text, wpic_middle text, wpic_m_height text, islike text, iszan text)"];
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"daohanglan"] forBarMetrics:UIBarMetricsDefault];
    _picListTableView = [[UITableView alloc]initWithFrame:[[UIScreen mainScreen]bounds] style:(UITableViewStylePlain)];
    _picListTableView.delegate = self;
    _picListTableView.dataSource = self;
    self.picListTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_picListTableView registerClass:[MQPictureInsterestingCell class] forCellReuseIdentifier:@"picLisCell"];
    _picListTableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_picListTableView];
    //右上角设置按钮
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(setting:)];
    barButton.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = barButton;
    //上拉下拉刷新数据
      [self selectDataBase];
    [self headerdRefresh];
    [self footRefresh];
    if ([self isConnectionAvailable]) {
        [self.dataArray removeAllObjects];
        self.urlStr = @"http://120.55.151.67/weibofun/weibo_list.php?apiver=10701&category=weibo_pics&page=0&page_size=30&max_timestamp=-1&latest_viewed_ts=1445655600&platform=iphone&appver=1.9&buildver=1.9.4&udid=AC7B37F1-E176-4822-93E9-5450B95501B3&sysver=9.0.2";
        [self configureData];
         }
    else
    {
        [self noNetWorking];
        //查询数据库
    }

   
    
}
#pragma mark-TableViewDataSoure
//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}
//cell的配置
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MQPictureInsterestingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"picLisCell" forIndexPath:indexPath];
    MQPictureInsterestingModel *model = self.dataArray[indexPath.row];
    //给图片添加一个手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapChangeFram:)];
    cell.contentImgView.tag = 100+indexPath.row;
    [cell.contentImgView addGestureRecognizer:tap];
    cell.contentImgView.userInteractionEnabled = YES;
    //分享
    [cell.shareButton addTarget:self action:@selector(shareContent:) forControlEvents:(UIControlEventTouchUpInside)];
    self.shareStr =  [model.wbody stringByAppendingString:model.wpic_middle];
    self.shareImage = cell.contentImgView.image;
    [cell cellForModel:model];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}

#pragma mark-TableViewDelegate
//cell的行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MQPictureInsterestingModel *model = self.dataArray[indexPath.row];
    return [MQPictureInsterestingCell HeightForModel:model];
}

#pragma mark-上拉刷新
- (void)headerdRefresh
{
    self.picListTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self.dataArray removeAllObjects];
        self.urlStr = @"http://120.55.151.67/weibofun/weibo_list.php?apiver=10701&category=weibo_pics&page=0&page_size=30&max_timestamp=-1&latest_viewed_ts=1445655600&platform=iphone&appver=1.9&buildver=1.9.4&udid=AC7B37F1-E176-4822-93E9-5450B95501B3&sysver=9.0.2";
        [self configureData];
    }];
}
#pragma mark - 下拉加载更多
-(void)footRefresh
{
    self.picListTableView.footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        i++;
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSString *max_times = [defaults objectForKey:@"update_time"];
        self.urlStr = [NSString stringWithFormat: @"http://120.55.151.67/weibofun/weibo_list.php?apiver=10701&category=weibo_pics&page=%d&page_size=15&max_timestamp=%@&latest_viewed_ts=1445655600&platform=iphone&appver=1.9&buildver=1.9.4&udid=AC7B37F1-E176-4822-93E9-5450B95501B3&sysver=9.0.2",i,max_times];
        [self configureData];
    }];
}

#pragma mark- 模态出一个界面，用于查看放大的图片
-(void)tapChangeFram:(UITapGestureRecognizer *)tap
{
    BigBackgroundViewController *bigVC = [[BigBackgroundViewController alloc]init];
    MQPictureInsterestingModel *model = self.dataArray[tap.view.tag-100];
    bigVC.model = model;
    [self presentViewController:bigVC animated:YES completion:nil];
    
}

#pragma mark - dataBase
//查询数据库
-(void)selectDataBase
{
    FMResultSet *resultSet = [[MQFMDBManager shareDataBase] executeQuery:@"SELECT * FROM PICTURE"];
    while ([resultSet next]) {
        NSString *wbody = [resultSet stringForColumn:@"wbody"];
        NSString *wpic_middle = [resultSet stringForColumn:@"wpic_middle"];
        NSString *wpic_m_height = [resultSet stringForColumn:@"wpic_m_height"];
        NSString *wpic_m_width = [resultSet stringForColumn:@"wpic_m_width"];
        NSString *likes = [resultSet stringForColumn:@"likes"];
        NSString *comments = [resultSet stringForColumn:@"comments"];
        MQPictureInsterestingModel *model = [[MQPictureInsterestingModel alloc]init];
        model.wbody = wbody;
        model.wpic_middle = wpic_middle;
        model.wpic_m_height = wpic_m_height;
        model.wpic_m_width = wpic_m_width;
        model.likes = likes;
        model.comments = comments;
        [self.dataArray addObject:model];
    }
    [resultSet close];
    [_picListTableView reloadData];
    
}
//插入数据
- (void)insertDatabase:(MQPictureInsterestingModel *)model
{
    [[MQFMDBManager shareDataBase] executeUpdate:@"INSERT INTO PICTURE (wbody, wpic_middle, wpic_m_height, wpic_m_width, likes, comments) VALUES (?,?,?,?,?,?)",model.wbody,model.wpic_middle,model.wpic_m_height,model.wpic_m_width,model.likes,model.comments];
}
//右上角设置按钮
- (void)setting:(UIBarButtonItem *)barButton
{
    MQPopupView *view = [MQPopupView defaultPopupView];
    view.parentVC = self;
    [self lew_presentPopupView:view animation:[LewPopupViewAnimationDrop new] dismissed:^{
        NSLog(@"动画结束");
        
    }];
}

//有无网络
-(BOOL) isConnectionAvailable{
    
    BOOL isExistenceNetwork = YES;
    Reachability * hostReach = [Reachability reachabilityWithHostName:@"www.apple.com"];
    switch ([hostReach currentReachabilityStatus]) {
        case NotReachable:
            isExistenceNetwork = NO;
            //            NSLog(@"notReachable");
            break;
        case ReachableViaWiFi:
            isExistenceNetwork = YES;
            //            NSLog(@"WIFI");
            break;
        case ReachableViaWWAN:
            isExistenceNetwork = YES;
            //            NSLog(@"3G");
            break;
    }
    return isExistenceNetwork;
}
//分享按钮
-(void)shareContent:(UIButton *)button
{
    NSLog(@"%@",self.shareStr);
    [UMSocialSnsService presentSnsIconSheetView:self appKey:@"561b79fde0f55ac7c00016bf"
        shareText:self.shareStr
        shareImage:self.shareImage
        shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,nil]
        delegate:self];
}
//没有网络显示提醒
-(void)noNetWorking
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:TITLE_MESSAGE preferredStyle:(UIAlertControllerStyleAlert)];
    
    [self presentViewController:alert animated:YES completion:nil];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [alert dismissViewControllerAnimated:YES completion:nil];
    });

}
// 一键换肤
- (void)changeSkin
{
    MQChangeSkin *view = [MQChangeSkin defaultPopupView];
    view.parentVC = self;
    [self lew_presentPopupView:view animation:[LewPopupViewAnimationDrop new] dismissed:^{
        NSLog(@"动画结束");
        
    }];

}

@end



